$(document).ready(function(){
	//Canvas stuff
	var canvas = $("#canvas")[0];
	var ctx = canvas.getContext("2d");
	var w = $("#canvas").width();
	var h = $("#canvas").height();
	
	//Lets save the cell width in a variable for easy control
	var cw = 10;
	var d;

	var level = []; 

	function init()
	{
    	// Attach the mousemove event handler.
   		canvas.addEventListener('mousedown', mousedown, false);
 		canvas.addEventListener('mouseup', mouseup, false);
   		canvas.addEventListener('mousemove', draw_walls, false);

		paint();
		//if(typeof game_loop != "undefined") clearInterval(game_loop);
		//game_loop = setInterval(paint, 60);
	}
	init();

	var md;
	function mousedown() {
		md = true;
	}

	function mouseup() {
		md = false;
	}

	//create the walls
	var started = false;
	function draw_walls(ev)
	{
		// Get the mouse position relative to the canvas element.
		if (ev.layerX || ev.layerX == 0) { // Firefox
			x = ev.layerX;
			y = ev.layerY;
		} else if (ev.offsetX || ev.offsetX == 0) { // Opera
			x = ev.offsetX;
			y = ev.offsetY;
    	}

    	cellx = Math.floor((x/cw)-1);
    	celly = Math.floor((y/cw)-1);

    	if(md == true){
	    	paint_cell(cellx, celly, "blue");
	    	level.push({x: cellx, y: celly})
    	}

    	function log(msg) {
 		   setTimeout(function() {
    	    throw new Error(msg);
   			 }, 0);
		}

		log("Hello world");

    	// The event handler works like a drawing pencil which tracks the mouse 
    	// movements. We start drawing a path made up of lines.
    	//if (!started) {
    	//	ctx.beginPath();
    	//	ctx.moveTo(x, y);
    	//	started = true;
    	//} else {
    	//	ctx.lineTo(x, y);
    	//	ctx.stroke();
    	//}


		for(var i = level.length - 1; i >= 0; i--)
		{
			var wa = level[i];
			paint_cell(wa.x, wa.y, "blue");
		}
	}
	
	//Lets paint the snake now
	function paint()
	{
		//To avoid the snake trail we need to paint the BG on every frame
		//Lets paint the canvas now
		ctx.fillStyle = "white";
		ctx.fillRect(0, 0, w, h);
		ctx.strokeStyle = "black";
		ctx.strokeRect(0, 0, w, h);

		//create_walls(level1);
	}
	
	//Lets first create a generic function to paint cells
	function paint_cell(x, y, color)
	{
		ctx.fillStyle = color;
		ctx.fillRect(x*cw, y*cw, cw, cw);
		ctx.strokeStyle = "black";
		ctx.strokeRect(x*cw, y*cw, cw, cw);
	}
	
	function check_collision(x, y, array)
	{
		//This function will check if the provided x/y coordinates exist
		//in an array of cells or not
		for(var i = 0; i < array.length; i++)
		{
			if(array[i].x == x && array[i].y == y)
			 return true;
		}
		return false;
	}
	
	//Lets add the keyboard controls now
	$(document).keydown(function(e){
		var key = e.which;
		//We will add another clause to prevent reverse gear
		if(key == "37" && d != "right") d = "left";
		else if(key == "38" && d != "down") d = "up";
		else if(key == "39" && d != "left") d = "right";
		else if(key == "40" && d != "up") d = "down";
		//The snake is now keyboard controllable
	})
})